﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sweepids.Models.Dao;
using Sweepids.Models.Object;

namespace Sweepids.Controllers
{
    public class ItemDetailController : Controller
    {
        //
        // GET: /ItemDetail/

        public ActionResult Index()
        {
            return RedirectToAction("Index", "Home");

        }

        public ActionResult Detail(int itemId)
        {
            try
            {
                var itemDao = new ItemDao();
                var item = itemDao.Read(itemId);
                item.Fill();
                return View(item);
            }
            catch (Exception)
            {
                TempData["Error"] = "An error occured while retreiving the details of this item.";
                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        public ActionResult PlaceBid(int itemId, string sweeps)
        {
            try
            {
                var user = (User)Session["User"];
                var itemDao = new ItemDao();
                var bidOnDao = new BidOnDao();
                var userDao = new UserDao();
                var sweepsVal = int.Parse(sweeps);

                if (sweepsVal > user.SweepsOwned)
                {
                    TempData["Error"] = "Not enough sweeps, please purchase more.";
                    return RedirectToAction("Detail", "ItemDetail", new { itemId = itemId });
                }

                var item = itemDao.Read(itemId);
                var bidOn = bidOnDao.Read(itemId, user.Username);

                item.SweepsOnItem += sweepsVal;
                user.SweepsOwned -= sweepsVal;

                itemDao.Update(item);

                /* first bid, create a new entry in DB */
                if (bidOn.NumBidsForUser == 0)
                {
                    bidOn.NumBidsForUser += sweepsVal;
                    bidOnDao.Create(bidOn);
                }
                else
                {
                    bidOn.NumBidsForUser += sweepsVal;
                    bidOnDao.Update(bidOn);
                }
                userDao.Update(user);
                user.Fill();

                TempData["Success"] = "Successfully placed your bid.";
                return RedirectToAction("Detail", "ItemDetail", new { itemId = itemId });
            }
            catch (Exception)
            {
                TempData["Error"] = "An error occured while placing your bid.";
                return RedirectToAction("Detail", "ItemDetail", new { itemId = itemId });
            }
        }
    }
}
